package cheme.ProcessModel.Table;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import cheme.ProcessModel.IModelElement;
import cheme.ProcessModel.IPropertyAware;
import cheme.ProcessModel.IXmlOperations;
import cheme.ProcessModel.XmlHelper;

public class SelectionField extends WritableField implements ISelectionModel, IXmlOperations
{
	List <String> options;
	int selectedOptionIndex = 0;
	
	public SelectionField(IModelElement parent, String [] options, int initial, String type)
	{
		super(parent, options[initial], type);
		
		this.options = new ArrayList<String>(options.length);
		
		for(String option : options)
		{
			this.options.add(option);
		}
	}
	
	public String [] getOptions()
	{
		String [] options = new String[this.options.size()];
		this.options.toArray(options);
		return options;
	}
	
	public String getOptionIndexString(int index)
	{
		return options.get(index);
	}
	
	public int getOptionStringIndex(String option)
	{
		return options.indexOf(option);
	}
	
	@Override
	public void setText(String text)
	{
		int index = getOptionStringIndex(text);
		
		index = (0 <= index && index < options.size()) ? index : 0;
		super.setText(options.get(index));
	}
	
	public String getSelectionText()
	{
		return getOptionIndexString(getSelection());
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void setSelection(int optionIndex)
	{
		if(selectedOptionIndex != optionIndex)
		{
			selectedOptionIndex = optionIndex;
			
			String old = getText();
			
			text = options.get(optionIndex); //always keep non-null text value.
						
			firePropertyChange(P_TEXT, old, text);
			
			if(getType() != null && getType() != IPropertyAware.P_TEXT)
			{
				firePropertyChange(getType(), old, this.text);
			}
		}
		text = options.get(optionIndex);
	}
	
	public int getSelection()
	{
		return selectedOptionIndex;
	}
	
	public void set(Field value)
	{
		if(value instanceof SelectionField)
		{
			setSelection(((SelectionField)value).getSelection());
		}
	}

	public String toXml() {
		
		//selection fields have a 'selected index' option that we need to capture
		//that isn't part of the default Field object.
		String xml = super.toXml();
		Document doc = (Document)XmlHelper.xmlFromString(xml);
		
		//the root node
		Element e1 = doc.getDocumentElement();
		
		//the new node to attach to the root node
		Element si = doc.createElement("SelectedIndex");
		Text t = doc.createTextNode("" + this.selectedOptionIndex);

		//attach...
		si.appendChild(t);
		e1.appendChild(si);
		
		//and return
		xml = XmlHelper.xmlToString(doc);
		return xml;
	}
}
